$(document).ready(function(){
	//$(".mobility-setup")
	$("body").on("click",".mobility-setup",function(){
		if($(".mobility-overlay").length == 0){
			if($("#FormId").val()!=0){
				
				createdMobileDialog = $(createMobileDialog());
				$("body").append(createdMobileDialog);
				$(".mobility-overlay").click(function(e){
					if (e.target === this || e.target === $(this).children(".mobility-content-middle")[0] ){
				        //outer
				        $(this).fadeOut(function(){
				        	$(this).remove();
				        });
				    }else{
				    	// inner
				    }
				})
				var mobilityLocationContent = $(createdMobileDialog).find(".mobility-body").eq(0).children("#sortable-mobile");

				mobilityLocationContent.sortable({
					containment: "parent"
				});

				mobilityLocationContent.disableSelection();
				var mobility_workspace = $("body").data();
				
				mobility_workspace.manage_field_component_on_form = [];

				mobility_workspace.manage_field_component_on_form = collectFormComponentFields();

				mobility_workspace.manage_saved_ui_mobile = [];
				
				var mobility_html_content_str = $($(".form-workspace-mobility-json").text());
				mobilityLocationContent.html(mobility_html_content_str);
				
				mobility_workspace.manage_saved_ui_mobile = collectSavedMobilityComponentFields();
				// console.log("ETO NA UNG COMPARE COLLECTED AND SAVED", mobility_workspace.manage_field_component_on_form,mobility_workspace.manage_saved_ui_mobile);
				console.log(mobility_workspace.manage_field_component_on_form)

				//checking existence
				for(index = 0 ; index < mobility_workspace.manage_saved_ui_mobile.length ; index++){
					for(index2 = 0 ; index2 < mobility_workspace.manage_field_component_on_form.length ; index2++){
						if(mobility_workspace.manage_saved_ui_mobile[index].elementFieldComponentMobileID ==  mobility_workspace.manage_field_component_on_form[index2].elementFieldComponentOnFormID){
							mobility_workspace.manage_saved_ui_mobile[index].lookupFoundBasedOnForm = true;
							mobility_workspace.manage_field_component_on_form[index2].lookupFoundBasedOnMobile = true;
						}
					}
				}

				//removing a non exisiting fields on the ui mobile based on the form
				for(index = 0 ; index < mobility_workspace.manage_saved_ui_mobile.length; index++){
					if(mobility_workspace.manage_saved_ui_mobile[index].lookupFoundBasedOnForm == false){
						mobility_workspace.manage_saved_ui_mobile[index].elementFieldComponentMobile.remove();
					}
				}

				//append fields not found on the saved mobile ui
				if(mobility_workspace.manage_field_component_on_form.length >= 1 ){
					for(ctr = 0 ; ctr < mobility_workspace.manage_field_component_on_form.length ; ctr++){
						if(mobility_workspace.manage_field_component_on_form[ctr].lookupFoundBasedOnMobile == false){
							eleComponent = mobility_workspace.manage_field_component_on_form[ctr].elementFieldComponentOnForm;
							fields_below = eleComponent.children(".fields_below");
							input_position_below = fields_below.children(".input_position_below");
							if(
								input_position_below.children(".tab-panel-parent-container").length >= 1 ||
								input_position_below.children(".table-wrapper").length >= 1
							){
								continue;
							}else{
								mobilityLocationContent.append(
									'<li class="element-mobile" style="position:relative;display:inline-block;width:100%;">'+
										mobility_workspace.manage_field_component_on_form[ctr].elementFieldComponentOnForm.wrap("<span class='wrapper-fields' />").closest(".wrapper-fields").html()+
									'</li>'
								);
								mobility_workspace.manage_field_component_on_form[ctr].elementFieldComponentOnForm.unwrap();
							}
						}
					}

					mobilityLocationContent.children("li").children(".setObject").css({
						"position":"relative",
						"top":"",
						"left":""
					});
					mobilityLocationContent.children("li").children(".setObject").children(".fields_below").css({
						"width":"100%"
					});
				}
			}else{
				createdMobileDialog = $(createMobileDialog());
				$("body").append(createdMobileDialog);
				$(".mobility-overlay").click(function(e){
					if (e.target === this || e.target === $(this).children(".mobility-content-middle")[0] ){
				        //outer
				        $(this).fadeOut(function(){
				        	$(this).remove();
				        });
				    }else{
				    	// inner
				    }
				})
				var mobilityLocationContent = $(createdMobileDialog).find(".mobility-body").eq(0).children("#sortable-mobile");

				mobilityLocationContent.sortable({
					containment: "parent"
				});

				mobilityLocationContent.disableSelection();
				var mobility_workspace = $("body").data();
				
				mobility_workspace.manage_field_component_on_form = [];

				mobility_workspace.manage_field_component_on_form = collectFormComponentFields();

				mobility_workspace.manage_saved_ui_mobile = [];
				
				var mobility_html_content_str = $($(".form-workspace-mobility-json").text());
				mobilityLocationContent.html(mobility_html_content_str);
				
				mobility_workspace.manage_saved_ui_mobile = collectSavedMobilityComponentFields();
				// console.log("ETO NA UNG COMPARE COLLECTED AND SAVED", mobility_workspace.manage_field_component_on_form,mobility_workspace.manage_saved_ui_mobile);
				console.log(mobility_workspace.manage_field_component_on_form)

				//checking existence
				for(index = 0 ; index < mobility_workspace.manage_saved_ui_mobile.length ; index++){
					for(index2 = 0 ; index2 < mobility_workspace.manage_field_component_on_form.length ; index2++){
						if(mobility_workspace.manage_saved_ui_mobile[index].elementFieldComponentMobileID ==  mobility_workspace.manage_field_component_on_form[index2].elementFieldComponentOnFormID){
							mobility_workspace.manage_saved_ui_mobile[index].lookupFoundBasedOnForm = true;
							mobility_workspace.manage_field_component_on_form[index2].lookupFoundBasedOnMobile = true;
						}
					}
				}

				//removing a non exisiting fields on the ui mobile based on the form
				for(index = 0 ; index < mobility_workspace.manage_saved_ui_mobile.length; index++){
					if(mobility_workspace.manage_saved_ui_mobile[index].lookupFoundBasedOnForm == false){
						mobility_workspace.manage_saved_ui_mobile[index].elementFieldComponentMobile.remove();
					}
				}

				//append fields not found on the saved mobile ui
				if(mobility_workspace.manage_field_component_on_form.length >= 1 ){
					for(ctr = 0 ; ctr < mobility_workspace.manage_field_component_on_form.length ; ctr++){
						if(mobility_workspace.manage_field_component_on_form[ctr].lookupFoundBasedOnMobile == false){
							eleComponent = mobility_workspace.manage_field_component_on_form[ctr].elementFieldComponentOnForm;
							fields_below = eleComponent.children(".fields_below");
							input_position_below = fields_below.children(".input_position_below");
							if(
								input_position_below.children(".tab-panel-parent-container").length >= 1 ||
								input_position_below.children(".table-wrapper").length >= 1
							){
								continue;
							}else{
								mobilityLocationContent.append(
									'<li class="element-mobile" style="position:relative;display:inline-block;width:100%;">'+
										mobility_workspace.manage_field_component_on_form[ctr].elementFieldComponentOnForm.wrap("<span class='wrapper-fields' />").closest(".wrapper-fields").html()+
									'</li>'
								);
								mobility_workspace.manage_field_component_on_form[ctr].elementFieldComponentOnForm.unwrap();
							}
						}
					}

					mobilityLocationContent.children("li").children(".setObject").css({
						"position":"relative",
						"top":"",
						"left":""
					});
					mobilityLocationContent.children("li").children(".setObject").children(".fields_below").css({
						"width":"100%"
					});
				}
			}
			

		}else{

		}
	});

	$("body").on("click","#mobility-cancel.mobility-cancel",function(){
		$(this).closest(".mobility-overlay").fadeOut(300,function(){
			$(this).remove();
		});
	});
 
	$("body").on("click","#mobility-save.mobility-save",function(){
		var mobility_workspace = $("body").data();
		mobility_workspace.saving_request_format = {};
		mobility_workspace.saving_request_format.fields = [];
		var mobilityLocationContent = $("#mobility-save.mobility-save").closest(".mobility-content-center").children(".mobility-body").eq(0);
		// getting fieldss
		if(mobilityLocationContent.children("ul#sortable-mobile").children(".element-mobile").length >= 1){
			console.log("MOBILITY SAVING")
			mobilityLocationContent.children("ul#sortable-mobile").children(".element-mobile").each(function(){

				object_index_id = $(this).children(".setObject").attr("data-object-id");
				fields_below = $(this).children(".setObject").children(".fields_below");
				mobility_workspace.saving_request_format.fields.push({
					"id": $(this).find(".getFields_"+object_index_id).eq(0).attr("name").replace("[]",""),
					"label": fields_below.children("#label_"+object_index_id).children("#lbl_"+object_index_id).text(),
					"generation": "REQUESTOR"
				});

				push_length = mobility_workspace.saving_request_format.fields.length - 1;
				form_field = fields_below.children("#obj_fields_"+object_index_id).find(".getFields_"+object_index_id+"");

				//ADDITIONAL FOR SPECIAL FIELDS
				if($(this).children(".setObject").attr("data-type") == "computed"){
					mobility_workspace.saving_request_format.fields[push_length]["generation"] = "SYSTEM";
				}
				// =========================================
				
				if( form_field.length >= 1 && form_field.attr("type") ){ //BY INPUT TYPES
					if(form_field.attr("type") == "checkbox"){

						mobility_workspace.saving_request_format.fields[push_length]["type"] = "CHECK_BOX_GROUP";
						mobility_workspace.saving_request_format.fields[push_length]["options"] = [];
						form_field.each(function(eqi_ffc){
							mobility_workspace.saving_request_format.fields[push_length]["options"].push($(this).val());
						});

					}else if(form_field.attr("type") == "radio"){

						mobility_workspace.saving_request_format.fields[push_length]["type"] = "RADIO_BUTTON_GROUP";
						mobility_workspace.saving_request_format.fields[push_length]["options"] = [];
						form_field.each(function(eqi_ffc){
							mobility_workspace.saving_request_format.fields[push_length]["options"].push($(this).val());
						});
					}else if(form_field.attr("type") == "text"){
						if(form_field.attr("data-type") == "dateTime"){
							mobility_workspace.saving_request_format.fields[push_length]["type"] = "DATE_TIME_PICKER";
						}else if(form_field.attr("data-type") == "date"){
							mobility_workspace.saving_request_format.fields[push_length]["type"] = "DATE_PICKER";
						}else if(form_field.closest(".setObject").attr("data-type") == "computed"){
							mobility_workspace.saving_request_format.fields[push_length]["type"] = "TEXT_FIELD";
							if(typeof form_field.attr("processor-type") != "undefined")
							{ mobility_workspace.saving_request_format.fields[push_length]["processor-type"] = ""+form_field.attr("processor-type"); }
							if(typeof form_field.attr("processor") != "undefined")
							{ mobility_workspace.saving_request_format.fields[push_length]["processor"] = ""+form_field.attr("processor"); }
						}else if(form_field.closest(".setObject").attr("data-type") == "barCodeScanner"){
							mobility_workspace.saving_request_format.fields[push_length]["type"] = "BAR_CODE";
						}else{
							mobility_workspace.saving_request_format.fields[push_length]["type"] = "TEXT_FIELD";

						}
					}
				}else{ //BY TAG NAME
					if(form_field.prop("tagName") == "SELECT" && form_field.attr("multiple")){
						mobility_workspace.saving_request_format.fields[push_length]["type"] = "SELECT";
						mobility_workspace.saving_request_format.fields[push_length]["property"] = "MULTIPLE";
					}else if(form_field.prop("tagName") == "SELECT"){
						mobility_workspace.saving_request_format.fields[push_length]["type"] = "SELECT";
						mobility_workspace.saving_request_format.fields[push_length]["property"] = "";
					}else if(form_field.prop("tagName") == "TEXTAREA"){
						mobility_workspace.saving_request_format.fields[push_length]["type"] = "TEXT_AREA";
					}
				}
				console.log(JSON.stringify(mobility_workspace.saving_request_format.fields[push_length]));
			});
		}
		
		if(typeof mobility_workspace.manage_field_component_on_form != "undefined"){
			delete mobility_workspace.manage_field_component_on_form;	
		}
		if(typeof mobility_workspace.manage_saved_ui_mobile != "undefined"){
			delete mobility_workspace.manage_saved_ui_mobile;
		}
		mobility_workspace.saved_mobile_content = $(this).closest(".mobility-content-center").children(".mobility-body").children("#sortable-mobile").html();
		$("body").data(mobility_workspace);
		$(".form-workspace-mobility-json").text(mobilityLocationContent.children("#sortable-mobile").html());
		showNotification({
		    message: "Mobility was successfully saved!",
		    type: "success",
		    autoClose: true,
		    duration: 3
	    });
		$(".mobility-overlay").click();
		// console.log("TERSTYYING");
		// console.log(mobility_workspace);
		// console.log(mobility_workspace.saving_request_format);
		// console.log(JSON.stringify(mobility_workspace.saving_request_format));

	});



	function createMobileDialog (){
		var ret
		=	'<div class="mobility-overlay" title="click the overlay background to close the dialog" style="background-color:rgba(225,225,225,0.5);z-index:1000;top:20px;display:table;position:fixed;width:100%;height:100%;">'+
				'<div class="mobility-content-middle" style="height:auto;display:table-cell;vertical-align:middle;">'+
					'<div class="mobility-content-center" style="height:500px;width:300px;border:2px solid #FFFFFF;padding-left:35px;padding-right:35px;padding-top:25px;background-color:#141414;border-radius: 15px;position: relative;box-shadow: 0 0 5px 5px rgb(109, 109, 109);margin: 0px auto;">'+
						'<div class="mobility-header" style="height:35px;"><div class="head-design" style="background-color: rgb(200,200,200);height: 10px;width: 100px;margin: 0px auto;border-radius: 10px;box-shadow: 3px 3px 5px black inset;"></div></div>'+
						'<div class="mobility-body" style="position:relative;height:400px;width:100%;border:1px solid #000;background-color:#FFF;border-radius: 10px;overflow:auto">'+
							'<ul id="sortable-mobile" style="position:relative;"></ul>'+
						'</div>'+
						'<div class="mobility-footer">'+
							'<div class="fields" style="border:0px;">'+
								//'<div class="label_basic"></div>'+
								//'<div class="input_position" style="margin-top:5px;text-align:center;">'+
									'<input type="button" class="btn-blueBtn mobility-save" data-form-type="formbuilder" id="mobility-save" value="Save" style="margin: 0px auto;float: none;clear: both;display: inherit;border-radius: 100%;width: 35px;height: 35px;margin-top: 10px;box-shadow: 0px 15px 15px black inset;text-align: center;padding: 0px;">'+
									//'<input type="button" class="btn-basicBtn mobility-cancel" id="mobility-cancel" value="Cancel">'+
								//'</div>'+
							'</div>'+
						'</div>'+
					'</div>'+
				'</div>'+
			'</div>';

		return ret;
	}

	function collectSavedMobilityComponentFields(){
		var collect_saved_ui_mobile = [];
		$("#sortable-mobile .element-mobile").each(function(eqs){
			collect_saved_ui_mobile.push({
				"elementFieldComponentMobile":$("#sortable-mobile .element-mobile").eq(eqs),
				"lookupFoundBasedOnForm":false,
				"elementFieldComponentMobileID":$("#sortable-mobile .element-mobile").eq(eqs).find(".setObject").attr("id"),
				"eqIndex":eqs
			});
		});
		return collect_saved_ui_mobile;
	}

	function collectFormComponentFields(){
		var collect_form_component_fields = [];
		$(".workspace.formbuilder_ws .setObject ").each(function(eqis){
			if($(".workspace.formbuilder_ws .setObject ").eq(eqis).find(".getFields").attr("name")){

			}else{
				return true;
			}
			collect_form_component_fields.push({
				"elementFieldComponentOnForm":$(".workspace.formbuilder_ws .setObject ").eq(eqis),
				"lookupFoundBasedOnMobile":false,
				"elementFieldComponentOnFormID":$(".workspace.formbuilder_ws .setObject ").eq(eqis).attr("id")
			});

		});
		return collect_form_component_fields;
	}

	function removeFieldNotExistingOnForm(){
		//
	}

	//

	function acceptableField(){
		//
	}
});